import { DataSource } from "typeorm"
import env from './env'
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import logger from '../utils/logger';

export const AppDataSource = new DataSource({
    type: "mysql",
    host: env.DB_HOST,
    port: parseInt(env.DB_PORT),
    username: env.DB_USERNAME,
    password: env.DB_PASSWORD,
    database: env.DB_DATABASE,
    synchronize: true,
    logging: ['query', 'error', 'schema', 'warn', 'info', 'log'],
    namingStrategy: new SnakeNamingStrategy(),
    entities: env.DB_ENTITIES.split(','),
    subscribers: [],
    migrations: [],
    logger: {
        logQuery: (query: string, parameters?: any[]) => {
            try {
                const params = parameters?.map(param => {
                    if (param instanceof Date) {
                        return param.toISOString();
                    }
                    return param;
                });

                const sql = params?.length
                    ? `${query} -- Parameters: ${JSON.stringify(params)}`
                    : query;

                logger.info('SQL Query:', sql);
            } catch (error) {
                logger.error('Error logging query:', query);
            }
        },
        logQueryError: (error: string | Error, query: string, parameters?: any[]) => {
            try {
                const params = parameters?.map(param => {
                    if (param instanceof Date) {
                        return param.toISOString();
                    }
                    return param;
                });

                const errorMessage = error instanceof Error ? error.message : error;
                logger.error('Query Error:', {
                    error: errorMessage,
                    query,
                    parameters: params
                });
            } catch (err) {
                logger.error('Error logging query error:', query);
            }
        },
        logQuerySlow: (time: number, query: string, parameters?: any[]) => {
            try {
                const params = parameters?.map(param => {
                    if (param instanceof Date) {
                        return param.toISOString();
                    }
                    return param;
                });

                logger.warn('Slow Query:', {
                    time: `${time}ms`,
                    query,
                    parameters: params
                });
            } catch (error) {
                logger.warn('Error logging slow query:', query);
            }
        },
        logSchemaBuild: (message: string) => {
            logger.info('Schema Build:', message);
        },
        logMigration: (message: string) => {
            logger.info('Migration:', message);
        },
        log: (level: 'log' | 'info' | 'warn', message: any) => {
            try {
                const msg = typeof message === 'object' ? JSON.stringify(message) : message;
                switch (level) {
                    case 'log':
                        logger.info(msg);
                        break;
                    case 'info':
                        logger.info(msg);
                        break;
                    case 'warn':
                        logger.warn(msg);
                        break;
                }
            } catch (error) {
                logger.error('Error in general logging');
            }
        }
    },
});